﻿/**************************************************************************
创建时间:	2020/6/28
作	  者:	张存
邮 	  箱:	zhangcunliang@126.com

Copyright (c) zhcun.cn

描	述：
记	录：
***************************************************************************/
using Org.BouncyCastle.Asn1.Cms;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ZhCun.Utils.Helpers;

namespace ZhCun.WebUtils.Authorizes
{
    public class LoginUser
    {
        /// <summary>
        /// 当前用户Id
        /// </summary>
        public string UserId { set; get; }
        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName { set; get; }
        /// <summary>
        /// 角色
        /// </summary>
        public string RoleId { set; get; }
        /// <summary>
        /// 过期时长
        /// </summary>
        public TimeSpan Expires { set; get; }
        /// <summary>
        /// 在指定该时间之后有效
        /// </summary>
        public DateTime? NotBefore { set; get; }
        /// <summary>
        /// 过期时间
        /// </summary>
        public DateTime ExpiresTime { get; set; }

        /// <summary>
        /// 创建一个新token,并赋值 ExpiresTime
        /// </summary>
        public override string ToString()
        {
            string[] arr = new[] {
                UserId,
                UserName,
                RoleId,
                Expires.TotalMinutes.ToString("0"),
                NotBefore?.ToTimestamp().ToString(),
                ExpiresTime.ToTimestamp().ToString()
            };
            return string.Join('\t', arr);
        }


        public static LoginUser FromString(string str)
        {
            LoginUser user = new LoginUser();
            var arr = str.Split('\t');
            user.UserId = arr[0];
            user.UserName = arr[1];
            user.RoleId = arr[2];
            user.Expires = TimeSpan.FromMinutes(int.Parse(arr[3]));
            if (!arr[4].IsEmpty())
            {
                user.NotBefore = long.Parse(arr[4]).ToTimestamp();
            }
            user.ExpiresTime = long.Parse(arr[5]).ToTimestamp();
            return user;
        }
    }
}